﻿using DataPersistence;
using Newtonsoft.Json.Linq;
using NLog;
using QueryDataLogic;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PersistenceDataLogic
{
    public class OperationEvaluation
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        PersistenceData pd = new PersistenceData();
        QueryData qd = new QueryData();
        BasicInfo bi = new BasicInfo();

        /// <summary>
        /// 判断是否已提交食堂菜品质量评价单
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        private bool isSubmit(int userID, string dbName)
        {
            try
            {
                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "select id from EvaluationUser where [date] = CONVERT(varchar(100), GETDATE(), 23) and userID = @userID "
                };
                comm.Parameters.AddWithValue("@userID", userID);
                JArray ja = qd.GetData(comm, dbName);

                if (ja.Count > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                logger.Error(ex);
                return false;
            }
        }

        /// <summary>
        /// 获取食堂菜品质量评价单ID
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="districtID"></param>
        /// <returns></returns>
        private int GetEvaluationOrderID(int UserID, int districtID)
        {
            int id = 0;
            try
            {
                string dbName = "";

                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "select id from EvaluationIdea " +
                    "where districtID = @districtID and UserID = @UserID and [date] = CONVERT(varchar(100), GETDATE(), 23) order by id "
                };
                comm.Parameters.AddWithValue("@districtID", districtID);
                comm.Parameters.AddWithValue("@UserID", UserID);

                dbName = bi.GetDBName(districtID);
                JArray ja = qd.GetData(comm, dbName);
                if (ja.Count > 0)
                {
                    id = (int)ja[0]["id"];
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
            }
            return id;
        }

        /// <summary>
        /// 新增食堂菜品质量评价单
        /// </summary>
        /// <param name="joParam"></param>
        /// <returns></returns>
        public JObject OptEvaluationOrder(JObject joParam)
        {
            JObject joResult = new JObject();
            try
            {
                string Idea = "";
                if (joParam.Property("idea") != null)
                {
                    Idea = (string)joParam["idea"];
                }
                int userID = (int)joParam["userID"];
                int districtID = (int)joParam["districtID"];
                string dbName = bi.GetDBName(districtID);
                JArray jaEvaluation = (JArray)joParam["evaluate"];
                if (jaEvaluation.Count > 0)
                {
                    int ectrid = 0;
                    int ideaID = 0;
                    int resultLine = 0;
                    SqlCommand comm = new SqlCommand();

                    if (!isSubmit(userID, dbName))
                    {
                        JObject joEraluationItem = new JObject();
                        for (int evaluateIndex = 0; evaluateIndex < jaEvaluation.Count; evaluateIndex++)
                        {
                            comm = new SqlCommand();
                            joEraluationItem = (JObject)jaEvaluation[evaluateIndex];
                            ectrid = (int)joEraluationItem["ectrid"];

                            comm.CommandText = "INSERT INTO EvaluationUser(UserID,ECTRID,DistrictID) VALUES(@UserID,@ECTRID,@DistrictID)";

                            comm.Parameters.AddWithValue("@userID", userID);
                            comm.Parameters.AddWithValue("@ECTRID", ectrid);
                            comm.Parameters.AddWithValue("@DistrictID", districtID);

                            resultLine += pd.ExeSqlCode(comm, dbName);
                        }

                        if (resultLine > 0)
                        {
                            if (Idea == "")
                            {
                                joResult["message"] = "提交食堂菜品质量评价单成功";
                                joResult["data"] = resultLine;
                                joResult["state"] = true;
                                return joResult;
                            }

                            comm = new SqlCommand();
                            resultLine = 0;

                            comm.CommandText = "INSERT INTO EvaluationIdea(UserID,Idea,DistrictID) VALUES(@UserID,@Idea,@DistrictID)";

                            comm.Parameters.AddWithValue("@userID", userID);
                            comm.Parameters.AddWithValue("@Idea", Idea);
                            comm.Parameters.AddWithValue("@DistrictID", districtID);

                            resultLine = pd.ExeSqlCode(comm, dbName);

                            if (resultLine > 0)
                            {
                                joResult["message"] = "提交食堂菜品质量评价单成功";
                                joResult["data"] = resultLine;
                                joResult["state"] = true;
                            }
                            else
                            {
                                comm = new SqlCommand();
                                resultLine = 0;
                                ideaID = GetEvaluationOrderID(userID, districtID);
                                //删除评价项目
                                comm.CommandText = "DELETE FROM EvaluationIdea WHERE ContentID = @id; ";
                                comm.Parameters.AddWithValue("@id", ideaID);
                                resultLine = pd.ExeSqlCode(comm, dbName);

                                joResult["message"] = "提交食堂菜品质量评价单失败";
                                joResult["data"] = resultLine;
                                joResult["state"] = false;
                            }
                        }
                        else
                        {
                            joResult["message"] = "提交食堂菜品质量评价单失败";
                            joResult["data"] = resultLine;
                            joResult["state"] = false;
                        }
                    }
                    else
                    {
                        joResult["data"] = 0;
                        joResult["message"] = "你今天已经提交过食堂菜品质量评价单，无法修改或再次提交";
                        joResult["state"] = false;
                        
                    }
                }
                else
                {
                    joResult["message"] = "评价选项未选择或未修改，请选择或修改后再次提交";
                    joResult["data"] = 0;
                    joResult["state"] = false;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
                joResult["data"] = 0;
                joResult["message"] = ex.Message + "\n" + ex.StackTrace;
                joResult["state"] = false;
            }

            return joResult;
        }
        
    }
}
